const mongoose = require("mongoose")
const config = require("./config")

// ;(async () => {
//   const res = await mongoose.connect(
//     config.dbUrl,
//     { useNewUrlParser: true }
//   )
//   if (res.connection.readyState === 1) console.log("db is connected!")
// })()

;(() => {
  const __MAX__ = 3
  let err_times = 0

  process.env.NODE_ENV === 'development' && mongoose.set('debug', true)

  mongoose.set("useCreateIndex", true)
  mongoose.set('useFindAndModify', false)
  mongoose.connect(config.dbUrl, { useNewUrlParser: true })

  mongoose.connection.on("disconnected", () => {
    if (err_times++ < __MAX__) mongoose.connect(config.db)
  })

  mongoose.connection.on("error", console.error)

  mongoose.connection.on("open", () => {
    err_times = 0
    console.log("Connected to db")
  })
})()
